using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Matrix.Notification.Services
{
    /// <summary>
    /// WebHook通知服务接口
    /// </summary>
    public interface IWebHookNotificationService
    {
        /// <summary>
        /// 发送WebHook通知
        /// </summary>
        /// <param name="message">WebHook消息</param>
        /// <param name="webhookUrl">WebHook URL</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>WebHook结果</returns>
        Task<WebHookNotificationResult> SendAsync(
            WebHookNotificationMessage message,
            string webhookUrl,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// 批量发送WebHook通知
        /// </summary>
        /// <param name="message">WebHook消息</param>
        /// <param name="webhookUrls">WebHook URL列表</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>WebHook结果列表</returns>
        Task<List<WebHookNotificationResult>> SendBatchAsync(
            WebHookNotificationMessage message,
            IEnumerable<string> webhookUrls,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// 验证WebHook URL
        /// </summary>
        /// <param name="webhookUrl">WebHook URL</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>是否有效</returns>
        Task<bool> ValidateWebHookUrlAsync(
            string webhookUrl,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// 测试WebHook连接
        /// </summary>
        /// <param name="webhookUrl">WebHook URL</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>测试结果</returns>
        Task<WebHookTestResult> TestConnectionAsync(
            string webhookUrl,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// 获取WebHook调用统计信息
        /// </summary>
        /// <param name="webhookUrl">WebHook URL（可选）</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>统计信息</returns>
        Task<WebHookNotificationStatistics> GetStatisticsAsync(
            string? webhookUrl = null,
            DateTime? startTime = null,
            DateTime? endTime = null,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// 检查WebHook服务可用性
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>是否可用</returns>
        Task<bool> IsAvailableAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// 重试失败的WebHook调用
        /// </summary>
        /// <param name="failedResult">失败的WebHook结果</param>
        /// <param name="maxRetries">最大重试次数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>重试结果</returns>
        Task<WebHookNotificationResult> RetryAsync(
            WebHookNotificationResult failedResult,
            int maxRetries = 3,
            CancellationToken cancellationToken = default);
    }

    /// <summary>
    /// WebHook通知结果
    /// </summary>
    public class WebHookNotificationResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 请求ID
        /// </summary>
        public string? RequestId { get; set; }

        /// <summary>
        /// WebHook URL
        /// </summary>
        public string WebHookUrl { get; set; } = string.Empty;

        /// <summary>
        /// HTTP状态码
        /// </summary>
        public int StatusCode { get; set; }

        /// <summary>
        /// 响应内容
        /// </summary>
        public string? ResponseContent { get; set; }

        /// <summary>
        /// 响应头信息
        /// </summary>
        public Dictionary<string, string> ResponseHeaders { get; set; } = new();

        /// <summary>
        /// 错误信息
        /// </summary>
        public string? ErrorMessage { get; set; }

        /// <summary>
        /// 错误类型
        /// </summary>
        public WebHookErrorType? ErrorType { get; set; }

        /// <summary>
        /// 请求时间
        /// </summary>
        public DateTime RequestTime { get; set; }

        /// <summary>
        /// 响应时间
        /// </summary>
        public DateTime ResponseTime { get; set; }

        /// <summary>
        /// 耗时（毫秒）
        /// </summary>
        public long DurationMs => ResponseTime > RequestTime ? (long)(ResponseTime - RequestTime).TotalMilliseconds : 0;

        /// <summary>
        /// 重试次数
        /// </summary>
        public int RetryCount { get; set; }

        /// <summary>
        /// 额外元数据
        /// </summary>
        public Dictionary<string, object> Metadata { get; set; } = new();
    }

    /// <summary>
    /// WebHook测试结果
    /// </summary>
    public class WebHookTestResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 响应时间（毫秒）
        /// </summary>
        public long ResponseTimeMs { get; set; }

        /// <summary>
        /// HTTP状态码
        /// </summary>
        public int StatusCode { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string? ErrorMessage { get; set; }

        /// <summary>
        /// 建议的超时时间（毫秒）
        /// </summary>
        public int? SuggestedTimeoutMs { get; set; }

        /// <summary>
        /// 支持的HTTP方法
        /// </summary>
        public List<string> SupportedMethods { get; set; } = new();

        /// <summary>
        /// 认证要求
        /// </summary>
        public string? AuthenticationRequirement { get; set; }
    }

    /// <summary>
    /// WebHook通知统计信息
    /// </summary>
    public class WebHookNotificationStatistics
    {
        /// <summary>
        /// WebHook URL
        /// </summary>
        public string? WebHookUrl { get; set; }

        /// <summary>
        /// 总发送数
        /// </summary>
        public long TotalSent { get; set; }

        /// <summary>
        /// 成功数
        /// </summary>
        public long SuccessCount { get; set; }

        /// <summary>
        /// 失败数
        /// </summary>
        public long FailureCount { get; set; }

        /// <summary>
        /// 成功率
        /// </summary>
        public double SuccessRate => TotalSent > 0 ? (double)SuccessCount / TotalSent : 0;

        /// <summary>
        /// 统计开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 统计结束时间
        /// </summary>
        public DateTime EndTime { get; set; }

        /// <summary>
        /// 按错误类型分组的统计
        /// </summary>
        public Dictionary<WebHookErrorType, long> ErrorBreakdown { get; set; } = new();

        /// <summary>
        /// 平均响应时间（毫秒）
        /// </summary>
        public double AverageResponseTimeMs { get; set; }

        /// <summary>
        /// 最大响应时间（毫秒）
        /// </summary>
        public long MaxResponseTimeMs { get; set; }

        /// <summary>
        /// 最小响应时间（毫秒）
        /// </summary>
        public long MinResponseTimeMs { get; set; }

        /// <summary>
        /// 按状态码分组的统计
        /// </summary>
        public Dictionary<int, long> StatusCodeBreakdown { get; set; } = new();
    }

    /// <summary>
    /// WebHook错误类型
    /// </summary>
    public enum WebHookErrorType
    {
        /// <summary>
        /// 无错误
        /// </summary>
        None,

        /// <summary>
        /// 网络错误
        /// </summary>
        NetworkError,

        /// <summary>
        /// HTTP错误
        /// </summary>
        HttpError,

        /// <summary>
        /// 超时错误
        /// </summary>
        TimeoutError,

        /// <summary>
        /// DNS解析错误
        /// </summary>
        DnsError,

        /// <summary>
        /// SSL/TLS错误
        /// </summary>
        SslError,

        /// <summary>
        /// 认证错误
        /// </summary>
        AuthenticationError,

        /// <summary>
        /// JSON序列化错误
        /// </summary>
        JsonSerializationError,

        /// <summary>
        /// 格式错误
        /// </summary>
        FormatError,

        /// <summary>
        /// 服务不可用
        /// </summary>
        ServiceUnavailable,

        /// <summary>
        /// 未知错误
        /// </summary>
        UnknownError
    }
}